package utils

import (

	"fmt"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/driver/mysql"
	"github.com/spf13/viper"
	"github.com/go-redis/redis"
	"time"
	"os"
	"log"
	"context"
)

func InitConfig() {
	viper.SetConfigName("app")
	viper.AddConfigPath("config")
	err := viper.ReadInConfig()
	if err!=nil {
		fmt.Println(err)
	}
	fmt.Println("Config app: ",viper.Get("app"))
	fmt.Println("Config mysql: ",viper.Get("mysql"))

}

var DB *gorm.DB
var Red * redis.Client

// InitMysql 初始化 MySQL 数据库连接
func InitMysql()  {
	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags),
		logger.Config{
			SlowThreshold: time.Second,
			LogLevel: logger.Info,
			Colorful: true,
		},
	)

    // 直接给全局变量 DB 赋值
    DB, _= gorm.Open(mysql.Open(viper.GetString("mysql.dns")), &gorm.Config{Logger: newLogger})

}

func InitRedis()  {

	Red = redis.NewClient(&redis.Options{
		Addr: viper.GetString("redis.addr"),
		Password: viper.GetString("redis.password"),
		DB: viper.GetInt("redis.DB"),
		PoolSize: viper.GetInt("redis.poolSize"),
		MinIdleConns: viper.GetInt("redis.minIdleConn"),
	})
	pong,err := Red.Ping().Result()
	if err != nil {
		fmt.Println("init redis ....",err)
	}else{
		fmt.Println("Redis inited ....",pong)
	}

}

const (
	PublicKey = "websocket"
)

func Publish(ctx context.Context, channal string, msg string) error {
	var err error
	err = Red.Publish(channal,msg).Err()
	return err
}

func Subscribe(ctx context.Context, channal string) (string, error) {
	
	sub := Red.Subscribe(channal)
	fmt.Println("Subscribe ......",channal)
	msg, err := sub.ReceiveMessage()
	if err != nil {
		fmt.Println(err)
		return "",err
	}
	fmt.Println("Subscribe ......",msg.Payload)
	return msg.Payload, err
}